﻿var orderManager = {};
orderManager.isOrderDishesPage = true;
orderManager.currentAreaId = 0;
orderManager.currentAreaName = "";
orderManager.cacheData = [];
orderManager.url = {};
orderManager.url.getDate = "/Order/GetDate.ashx";
orderManager.url.getDataList = "GetDataList.ashx";
orderManager.url.order = "/Order/Order.ashx";
orderManager.type = {};
orderManager.type.getDishes = 0;
orderManager.type.getRestaurant = 1;
orderManager.freight = {};
orderManager.freight.limit = 200;
orderManager.freight.value = 6;

function cacheDishes() {
    this.restaurantName = "";
    this.restaurantId = "";
    this.id = 0;
    this.name = "";
    this.catName = 0;
    this.price = 0.00;
    this.discount = 100;
    this.invoiceDiscount = 100;
    this.unit = 0;
    this.number = 0;
    this.remarks = "";
    this.box = 0;
    this.boxPrice = 0;
};

orderManager.createRow = function (oTable, index) {
    return oTable.insertRow(index);
}
orderManager.createCell = function (oTr, index) {
    return oTr.insertCell(index);
}
orderManager.getDate = function () {
    $.post(orderManager.url.getDate,
        function (data) {
            jDoc("txt_DinnerD").value = data.obj["dinner"]["date"];
            jDoc("txt_DinnerH").value = data.obj["dinner"]["hour"];
            jDoc("txt_DinnerM").value = data.obj["dinner"]["minute"];
            jDoc("sp_OrderTime").innerHTML = data.obj["order"]["hour"] + ":" + data.obj["order"]["minute"];
        }, "json");
}
orderManager.searchDishes = function (o, rId) {
    jDoc("div_DishesList").innerHTML = "菜品数据加载中...";
    $.post(orderManager.url.getDataList, { id: rId, restaurantName: o.innerHTML, t: 2 }
        , function (data) {
            if (data.success) {
                jDoc("div_DishesList").innerHTML = data.message;
                jDoc("sp_RestaurantRemarks").innerHTML = jDoc("div_Remarks_" + rId).innerHTML;
                setHighlightTag(jDoc("div_DishesList"), jDoc("txt_DishesName").value, "red");
            } else {
                jDoc("div_DishesList").innerHTML = "数据加载失败";
            }
        }, "json");
}
orderManager.selectDishes = function (id) {
    var dishes = jDoc.parseJSONText(jDoc("txt_DishesJSON_" + id).value);
    dishes["remarks"] = "";
    orderManager.addDataToCache(dishes);
}
orderManager.updateDishesNumberToCache = function (id, number) {
    var cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        if (cacheList[i].id == id) {
            cacheList[i].number = number;
            break;
        }
    }
    orderManager.totalPrice();
}
orderManager.addDataToCache = function (dishes) {
    var flag = true, cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        if (cacheList[i].id == dishes.id) {
            cacheList[i].number += 1;
            dishes.number = cacheList[i].number;
            flag = false;
            break;
        }
    }
    if (flag) {
        orderManager.cacheData.push(dishes);
    }
    orderManager.addDataToSelectList(dishes);
    orderManager.totalPrice();
    orderManager.orderIndex();
}
orderManager.delDataFromCache = function (id) {
    var tmpl = [], cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        if (cacheList[i].id != id) {
            tmpl.push(cacheList[i]);
        }
    }
    orderManager.cacheData = tmpl;
    orderManager.delDataFromSelectList(id);
    orderManager.totalPrice();
    orderManager.orderIndex();
}
orderManager.showAllCacheData = function () {
    var cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        orderManager.addDataToSelectList(cacheList[i]);
    }
    orderManager.totalPrice();
    orderManager.orderIndex();
}
orderManager.delAllCacheData = function () {
    var cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        orderManager.delDataFromSelectList(cacheList[i].id);
    }
    orderManager.cacheData = [];
    orderManager.totalPrice();
}
orderManager.setRmarksToCacheData = function () {
    var cacheList = orderManager.cacheData;
    for (var i = 0, len = cacheList.length; i < len; i++) {
        cacheList[i].remarks = jDoc("txt_Remarks_" + cacheList[i].id).value;
    }
}
orderManager.delDataFromSelectList = function (id) {
    document.body.focus();
    var tblSelectedList = jDoc("tbl_SelectedDishes");
    var tr = jDoc("txt_Number_" + id).parentNode.parentNode;
    tblSelectedList.deleteRow(tr.rowIndex);
}
orderManager.addDataToSelectList = function (dishes) {
    var attrList = ["id", "areaName", "restaurantName", "name", "catName", "price", "unitName", "number", "remarks", "op"];
    var tblSelectedList = jDoc("tbl_SelectedDishes");
    var tmpl = {}, numberElem = jDoc("txt_Number_" + dishes.id);
    if (numberElem) {
        numberElem.value = dishes.number;
    } else {
        var tr = orderManager.createRow(tblSelectedList.tBodies[0] || tblSelectedList, tblSelectedList.rows.length);
        for (var m = 0, mLen = attrList.length; m < mLen; m++) {
            var cell = orderManager.createCell(tr, m);
            var attrName = attrList[m];
            switch (attrName) {
                case "id":
                    cell.style.display = orderManager.isOrderDishesPage ? "" : "none";
                    cell.innerHTML = ""; //tr.rowIndex;//(tblSelectedList.tBodies[0] || tblSelectedList).rows.length - 1;
                    break;
                case "number":
                    cell.innerHTML = jDoc.createInputHtml({
                        "type": "text", id: "txt_Number_" + dishes["id"],
                        value: dishes[attrName],
                        "onblur": "orderManager.changeNumEvent(this)",
                        "onfocus": "orderManager.changeNumFocusEvent(this)",
                        size: "3"
                    });
                    break;
                case "areaName":
                    cell.style.display = orderManager.isOrderDishesPage ? "" : "none";
                    cell.innerHTML = orderManager.currentAreaName;
                    break;
                case "remarks":
                    cell.innerHTML = jDoc.createInputHtml({
                        "type": "text",
                        id: "txt_Remarks_" + dishes["id"],
                        value: dishes[attrName]
                    });
                    break;
                case "op":
                    cell.innerHTML = "<a href='javascript:;' onclick='orderManager.delDataFromCache(" + dishes.id + ")'>删除</a>";
                    break;
                default:
                    cell.innerHTML = dishes[attrName];
                    break;
            }
        }
        (tblSelectedList.tBodies[0] || tblSelectedList).appendChild(tr);
    }
}
orderManager.orderIndex = function () {
    var tblSelectedList = jDoc("tbl_SelectedDishes");
    for (var i = 1, len = tblSelectedList.rows.length; i < len; i++) {
        tblSelectedList.rows[i].cells[0].innerHTML = i;
    }
}
orderManager.totalPrice = function () {
    var cacheList = orderManager.cacheData, total = 0;
    var total = 0, amount = 0, discountAmount = 0, price = 0, num = 0;
    var boxNum = 0, boxAmount = 0, discount = 100, restaurantList = [];
    var invoiceTitleElem = jDoc("text_InvoiceTitle");
    function totalRestaurant(id, amount) {
        var index = -1;
        for (var m = 0, mLen = restaurantList.length; m < mLen; m++) {
            if (restaurantList[m].id == id) {
                restaurantList[m].amount += amount;
                index = 1;
                break;
            }
        }
        if (index == -1) {
            var obj = { amount: 0 };
            obj.id = id;
            obj.amount += amount;
            restaurantList.push(obj);
        }
    }
    for (var i = 0, len = cacheList.length; i < len; i++) {
        price = cacheList[i].price;
        num = cacheList[i].number;
        boxNum += cacheList[i].boxNum * cacheList[i].number;
        boxAmount += cacheList[i].boxNum * cacheList[i].boxPrice * cacheList[i].number;
        amount += price * num;
        if (invoiceTitleElem && invoiceTitleElem.value.trim() != "") {
            discount = cacheList[i].invoiceDiscount;
        } else {
            discount = cacheList[i].discount;
        }
        discountAmount += (num * price) - (num * price * (discount / 100));
        totalRestaurant(cacheList[i].restaurantId, price * num);
    }
    total = amount;
    total += boxAmount;
    var freight = 0;
    for (var i = 0, len = restaurantList.length; i < len; i++) {
        if (restaurantList[i].amount < orderManager.freight.limit) {
            total += orderManager.freight.value;
            freight += orderManager.freight.value;
        }
    }
    jDoc("sp_Freight").innerHTML = freight;

    jDoc("sp_Amount").innerHTML = amount.toFixedString(2);
    jDoc("sp_DiscountAmount").innerHTML = discountAmount.toFixedString(2);
    jDoc("sp_Total").innerHTML = total.toFixedString(2);
    jDoc("sp_BoxNum").innerHTML = boxNum;
    jDoc("sb_BoxAmount").innerHTML = boxAmount.toFixedString(2);
}
orderManager.changeNumFocusEvent = function (ele) {
    ele.setAttribute("old-value", ele.value);
}
orderManager.changeNumEvent = function (ele) {
    if (ele.value.trim() == "" || isNaN(ele.value) || ele.value <= 0) {
        ele.value = ele.getAttribute("old-value");
        return;
    }
    var dishesId = ele.id.split("_")[2];
    this.updateDishesNumberToCache(dishesId, ele.value);
}
orderManager.showUserAddress = function () {
    var addr = jDoc("div_AddressList");
    var html = [], radId = "", addrList = orderManager.callerAddrList;
    html.push("<ul>");
    for (var i = 0, len = addrList.length; i < len; i++) {
        html.push("<li>");
        radId = "chk_" + addrList[i]["id"];
        html.push(jDoc.createInputHtml({ id: radId, type: "checkbox", onclick: "orderManager.selectAddress(this," + addrList[i]["id"] + ")" }));
        html.push("<label for='" + radId + "'>");
        html.push(addrList[i]["name"]);
        html.push(addrList[i]["gender"] == "0" ? " 先生" : " 女士");
        html.push(" ");
        html.push(addrList[i]["address"]);
        html.push(" ");
        html.push(" 手机:");
        html.push(addrList[i]["mobile"]);
        html.push(" 电话:");
        html.push(addrList[i]["tel"]);
        html.push("</label>");
        html.push("</li>");
    }
    html.push("</ul>");
    addr.innerHTML = html.join("");
}
orderManager.selectAddress = function (o, id) {
    if (o.checked) {
        jDoc.getElementsBy("div_AddressList", "input", function (e) {
            if (e.id != o.id && e.checked) {
                e.click();
            }
        });
        var addrList = orderManager.callerAddrList;
        for (var i = 0, len = addrList.length; i < len; i++) {
            if (addrList[i].id == id) {
                jDoc("txt_AddressId").value = id;
                if (addrList[i].gender == 0) {
                    jDoc("txt_MrName").value = addrList[i].name;
                } else {
                    jDoc("txt_MsName").value = addrList[i].name;
                }
                jDoc("txt_Tel").value = addrList[i].tel;
                jDoc("txt_Address").value = addrList[i].address;
                jDoc("text_InvoiceTitle").value = addrList[i].invoiceTitle;
                break;
            }
        }
    } else {
        orderManager.clearClientInfo();
    }
}
orderManager.clearClientInfo = function (b) {
    if (b) {
        jDoc("txt_UserId").value = "0";
        jDoc("txt_CallerID").value = "";
        jDoc("div_AddressList").innerHTML = "";
        orderManager.delAllCacheData();
        jDoc("sel_Area").disabled = false;
    }
    jDoc("txt_AddressId").value = "0";
    jDoc("txt_MrName").value = "";
    jDoc("txt_MsName").value = "";
    jDoc("txt_Tel").value = "";
    jDoc("txt_Address").value = "";
    jDoc("text_InvoiceTitle").value = "";
}

